package com.xxw.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.xxw.yygh.common.exception.YyghException;
import com.xxw.yygh.enums.PaymentTypeEnum;
import com.xxw.yygh.enums.RefundStatusEnum;
import com.xxw.yygh.model.order.OrderInfo;
import com.xxw.yygh.model.order.PaymentInfo;
import com.xxw.yygh.model.order.RefundInfo;
import com.xxw.yygh.order.prop.WeiPayProperties;
import com.xxw.yygh.order.service.OrderInfoService;
import com.xxw.yygh.order.service.PaymentInfoService;
import com.xxw.yygh.order.service.RefundInfoService;
import com.xxw.yygh.order.service.WeiPayService;
import com.xxw.yygh.order.utils.HttpClient;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeiPayServiceImpl implements WeiPayService {

    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private PaymentInfoService paymentInfoService;

    @Resource
    private WeiPayProperties weiPayProperties;

    @Resource
    private RefundInfoService refundInfoService;

    @Override
    public String createNative(Long orderId) {
        //1.根据订单id获取订单信息
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        //2.保存支付记录信息
        paymentInfoService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

        //3.请求微信服务器获取微信支付的url地址
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",weiPayProperties.getAppid());
        paramMap.put("mch_id",weiPayProperties.getPartner());
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());

        Date reserveDate = orderInfo.getReserveDate();
        String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
        String body = reserveDateString + "就诊"+ orderInfo.getDepname();
        paramMap.put("body", body);
        paramMap.put("out_trade_no",orderInfo.getOutTradeNo());
        paramMap.put("total_fee","1");//设置为一分钱，方便测试
        paramMap.put("spbill_create_ip", "127.0.0.1");
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//微信回调地址，需要公网地址
        paramMap.put("trade_type", "NATIVE");

        try {
            //4.将url返回给前端
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap, weiPayProperties.getPartnerkey()));
            httpClient.setHttps(true);//支持https协议
            httpClient.post();//发送请求
            String xmlResult = httpClient.getContent();
            Map<String, String> stringStringMap = WXPayUtil.xmlToMap(xmlResult);

            return stringStringMap.get("code_url");

        } catch (Exception e) {
            return "";
        }

    }

    @Override
    public Map<String, String> queryPayStatus(Long orderId) {

        //获取订单信息
        OrderInfo orderInfo = orderInfoService.getById(orderId);

        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
        Map<String, String> map = new HashMap<>();
        map.put("appid",weiPayProperties.getAppid());
        map.put("mch_id",weiPayProperties.getPartner());

        map.put("out_trade_no",orderInfo.getOutTradeNo()); //商户订单号
        map.put("nonce_str",WXPayUtil.generateNonceStr());

        try {
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map,weiPayProperties.getPartnerkey()));
            httpClient.setHttps(true);
            httpClient.post();
            String content = httpClient.getContent();
            Map<String, String> stringStringMap = WXPayUtil.xmlToMap(content);
            return stringStringMap;
        } catch (Exception e) {
            return null;
        }

    }

    @Override
    public boolean refund(Long orderId) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = paymentInfoService.getOne(queryWrapper);

        RefundInfo refundInfo =refundInfoService.saveRefundInfo(paymentInfo);
        //已退款
        if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
            return true;
        }
        //执行微信退款
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
        Map<String,String> paramMap = new HashMap<>(8);
        paramMap.put("appid",weiPayProperties.getAppid());       //公众账号ID
        paramMap.put("mch_id",weiPayProperties.getPartner());   //商户编号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
        paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
        paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
        paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
        //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee","1");
        paramMap.put("refund_fee","1");

        try {
            String paramXml = WXPayUtil.generateSignedXml(paramMap, weiPayProperties.getPartnerkey());
            httpClient.setXmlParam(paramXml);
            httpClient.setHttps(true);
            httpClient.setCert(true); //设置证书
            httpClient.setCertPassword(weiPayProperties.getPartner()); //设置证书密码
            httpClient.post();

            String content = httpClient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            if ("SUCCESS".equals(resultMap.get("result_code"))){
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);

                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }
}
